from django.shortcuts import render_to_response, render
from django.http import HttpResponse, HttpResponseRedirect, Http404
from django.template import RequestContext
from django.core.exceptions import PermissionDenied
from django.core.urlresolvers import reverse
from user_contacts.models import Phone, Person
from user_contacts.new_contact_form import ContactForm

# Create your views here.
def home(request):
    context = {}
    #return render_to_response("user_contacts/index.html")
    return render(request, 'user_contacts/index.html',
                  {'person_form': {'name': 'chengl6500',
                                   'age': 32,
                                   'sex': 'boy'}},
                  context_instance = RequestContext(request))

def index(request):
    return HttpResponseRedirect("/user_contacts/")

def all_contacts(request):
    contacts = Phone.objects.all()
    return render_to_response('user_contacts/all_contacts.html',
                              {'contacts': contacts})

def contacts_detail(request, number=None):
    try:
        template_name = "user_contacts/detail.html"
        contacts = Phone.objects.get(pk=number)
    except Phone.DoesNotExist:
        raise Http404
    return render_to_response(template_name,
                              {'contact': contacts})

def all_person(request):
    template_name = "user_contacts/all_persons.html"
    person_list = Person.objects.all()
    person_str = map(str, person_list)
    return render_to_response(template_name,
                              {'persons': person_list})
    # return HttpResponse("<table>" + ''.join(person_html) + "</table>" +
    #                     """<a href="{% url 'user_contacts:home' %}">return home</a>""")

def add_contact(request):
    person_form = ContactForm()
    return render(request, 'user_contacts/add_contact.html',
                  {'person_form': person_form},
                  context_instance = RequestContext(request))

def create(request):
    if request.method == "POST":
        form = ContactForm(request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('/user_contacts/')
        return render(request, 'user_contacts/add_contact.html',
                      {'person_form': form},
                      context_instance = RequestContext(request))
    else:
        return HttpResponseRedirect("/user_contacts/add/")

def delete(request):
    if request.method == "POST":
        pass
    else:
        print dir(request.POST)
        return HttpResponseRedirect(reverse("user_contacts:all_contacts"))

def deny(request):
    pk = '100'
    if int(pk) > 10:
        raise PermissionDenied
